<template>
  <ele-page flex-table>
    <!-- 搜索表单 -->
    <PageSearch :supplierList @search="reload" />

    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        v-model:selections="selections"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="false"
        highlight-current-row
        cache-key="PurchaseIndexTable"
      >
        <template #toolbar>
          <el-button type="primary" class="ele-btn-icon" :icon="Plus" @click="openPageTab()">新增</el-button>
          <el-divider direction="vertical" />
          <el-button :disabled="selections.length !== 1" @click="onCommand('EDIT')">编辑</el-button>

          <el-dropdown class="mx-15px" split-button :disabled="btnDisabled(selections, 'is_sh')" @click="onCommand('SH')" @command="onCommand">
            审核
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="YS">审核通过</el-dropdown-item>
                <el-dropdown-item command="NS">审核不通过</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-button :disabled="btnDisabled(selections, 'is_fs')" @click="onCommand('FS')">反审</el-button>
          <el-button :disabled="btnDisabled(selections, 'is_ok')" @click="onCommand('OK')">结单</el-button>
          <el-button :disabled="selections.length !== 1 || selections[0].is_xz !== 1" @click="onCommand('REVISE')">修正</el-button>
          <el-button :disabled="selections.length !== 1 || selections[0].is_cd !== 1" @click="onCommand('CD')">取消</el-button>
        </template>

        <template #order_sn="{ row }">
          <ele-copyable :text="row.order_sn">
            <el-link type="primary" @click="openPageTab(row, 'info')">{{ row.order_sn }}</el-link>
          </ele-copyable>
        </template>
        <template #third_party_sn="{ row }">
          <ele-copyable v-if="row.third_party_sn">{{ row.third_party_sn }}</ele-copyable>
          <div v-else>-</div>
        </template>

        <template #enter_status="{ row }">
          <el-tag :type="getType(row.enter_status, { YS: 'warning' })">{{ row.enter_status_name }}</el-tag>
        </template>
        <template #status="{ row }">
          <el-tag :type="getType(row.status)">{{ row.status_name }}</el-tag>
        </template>
        <template #action="{ row }">
          <div class="flex-ea">
            <template v-if="row.acts.length">
              <ele-dropdown
                :items="row.acts"
                @command="value => onCommand(value, row)"
              >
                <el-button
                  type="primary"
                  link
                >
                  <el-icon :size="16" class="block ml-4px"><IconElEditPen /></el-icon>
                </el-button>
              </ele-dropdown>
              <el-divider direction="vertical" />
            </template>

            <el-link type="primary" underline="never" @click="onCommand('INFO', row)">
              <ele-dot v-if="row.acts.length" type="danger" ripple text="详情" />
              <span v-else>详情</span>
            </el-link>
          </div>
        </template>
      </ele-pro-table>
    </ele-card>

    <PageReview v-model="showReview" remarkDisabled @done="review" />
  </ele-page>
</template>

<script setup>
import { listSupplier } from '@/api/common'
import PageReview from '@/components/Common/Review.vue'
import { Plus } from '@element-plus/icons-vue'
import { ref } from 'vue'
import PageSearch from './components/search.vue'

defineOptions({ name: 'PurchaseIndex' })

const router = useRouter()

// 激活页面刷新table
utils.useActivatedReload(() => tableRef.value?.reload?.())

const { btnDisabled, getType } = utils

const { addPageTab } = utils.usePageTab()

/** 表格实例 */
const tableRef = ref(null)

const [supplierList] = utils.useGetList(listSupplier)

/** 表格选中数据 */
const selections = ref([])

const showReview = ref(false)
const current = ref(null)

// utils.useTableReload(() => {
//   tableRef.value?.reload?.()
// })

/** 表格列配置 */
const columns = ref([
  {
    type: 'selection',
    columnKey: 'selection',
    width: 40,
    align: 'center',
    fixed: 'left',
    showOverflowTooltip: false,
  },
  {
    type: 'index',
    label: '序',
    width: 50,
    align: 'left',
    fixed: 'left',
  },
  {
    prop: 'order_sn',
    label: '单据编号',
    width: 200,
    align: 'left',
    slot: 'order_sn',
  },
  {
    prop: 'third_party_sn',
    label: '来源单号',
    width: 180,
    align: 'left',
    slot: 'third_party_sn',
    showOverflowTooltip: false,
  },
  {
    prop: 'order_date',
    label: '录单日期',
    minWidth: 100,
    align: 'center',
  },
  {
    prop: 'supplier_name',
    label: '货主',
    minWidth: 100,
    align: 'center',
  },
  {
    prop: 'warehouse_name',
    label: '收货仓库',
    minWidth: 100,
    align: 'center',
  },
  {
    prop: 'status_name',
    slot: 'status',
    label: '订单状态',
    align: 'center',
    width: 100,
  },
  {
    prop: 'enter_status_name',
    slot: 'enter_status',
    label: '收货状态',
    align: 'center',
    width: 100,
  },
  {
    prop: 'num',
    label: '数量',
    align: 'center',
    width: 100,
  },
  {
    prop: 'enter_num',
    label: '收货数量',
    align: 'center',
    width: 100,
  },
  {
    prop: 'purchase_total',
    label: '采购金额',
    align: 'center',
    width: 100,
  },
  {
    prop: 'tax_rate',
    label: '税率',
    align: 'center',
    width: 100,
    formatter: row => row.tax_rate > 0 ? `${row.tax_rate}%` : 0,
  },
  {
    prop: 'remark',
    showOverflowTooltip: true,
    label: '备注',
    align: 'center',
    width: 100,
  },
  {
    prop: 'create_user_name',
    label: '创建人',
    width: 100,
    align: 'center',
  },
  {
    prop: 'create_time',
    label: '创建时间',
    formatter: (row) => {
      return utils.formatDate(row.create_time)
    },
    align: 'center',
    width: 160,
    showOverflowTooltip: false,
  },
  {
    columnKey: 'action',
    label: '操作',
    align: 'right',
    slot: 'action',
    fixed: 'right',
    showOverflowTooltip: false,
    width: 110,
  },
])

/** 表格数据源 */
async function datasource({ page, limit, where, orders }) {
  const res = await utils.get('/purchase/index', { ...where, ...orders, page, limit })
  res.data.forEach((v) => {
    v.acts = getActs(v, true)
  })
  return res
}

/** 搜索 */
function reload(where) {
  selections.value = []
  tableRef.value?.reload?.({ page: 1, where })
}

function updateStatus(url, formData, cb) {
  const loading = utils.message('请求中..', 'loading')
  utils.post(url, formData).then((res) => {
    utils.message(res.msg, res.success)
    if (res.success) {
      reload()
      showReview.value = false
    }
  }).finally(() => {
    cb && cb()
    loading.close()
  })
}

function review(data, cb) {
  const id = current.value?.id ? [current.value.id] : selections.value.map(v => v.id)
  updateStatus('/purchase/review', {
    status: data.status,
    id,
  }, cb)
}

function onCommand(command, row) {
  current.value = row?.id ? row : null
  const id = row?.id ? row.id : selections.value[0].id
  const ids = row?.id ? [row.id] : selections.value.map(v => v.id)

  if (['INFO', 'EDIT', 'REVISE'].includes(command)) {
    const _row = current.value ?? selections.value[0]
    openPageTab(_row, command.toLowerCase())
  }
  else if (command === 'SH') {
    showReview.value = true
  }
  else if (command === 'CD') {
    utils.confirm('确定要<span class="px-2px text-danger font-semibold">取消</span>订单吗', '系统提示', {
      type: 'warning',
      dangerouslyUseHTMLString: true,
      cancelButtonText: '不取消了',
      confirmButtonText: '确定取消',
    }).then(() => {
      updateStatus('/purchase/cancel', { id })
    })
  }
  else {
    // YS 审核通过 NS 审核不通过 FS 反审 OK 已结单
    const list = [
      { key: 'YS', title: '审核通过' },
      { key: 'NS', title: '审核不通过' },
      { key: 'FS', title: '反审' },
      { key: 'OK', title: '结单' },
    ]
    const item = list.find(v => v.key === command)
    utils.confirm(`确定要<span class="px-2px text-danger font-semibold">${item.title}</span>订单吗`, '系统提示', {
      type: 'warning',
      dangerouslyUseHTMLString: true,
    }).then(() => {
      const formData = {
        id: ids,
        status: command,
      }
      updateStatus('/purchase/review', formData)
    })
  }
}

function getActs(row, filter = false) {
  const list = [
    { title: '编辑', command: 'EDIT', disabled: row.is_edit !== 1, icon: 'IconElEdit' },
    { title: '修正', command: 'REVISE', disabled: row.is_xz !== 1, icon: 'IconElEdit' },
    { title: '审核', command: 'SH', disabled: row.is_sh !== 1, icon: 'IconElStamp' },
    { title: '反审', command: 'FS', disabled: row.is_fs !== 1, icon: 'IconElStamp' },
    { title: '结单', command: 'OK', disabled: row.is_ok !== 1, icon: 'IconElCheck' },
    { title: '取消', command: 'CD', disabled: row.is_cd !== 1, icon: 'IconElClose' },
  ]
  if (filter) {
    return list.filter(v => !v.disabled)
  }
  return list
}

/** 打开编辑弹窗 */
function openPageTab(row, tag = 'edit') {
  const id = row?.id ?? 0
  const path = `/purchase/index/${tag}/${id}`

  addPageTab({
    key: path,
    closable: true,
  })
  router.push(path)
}
</script>
